package org.zfes.snowier.cloud.zbss.loan.wx.webapi;

import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.zfes.snowier.auth.biz.model.AuthUser;
import org.zfes.snowier.auth.biz.service.IAuthUserRoleService;
import org.zfes.snowier.auth.biz.service.IAuthUserService;
import org.zfes.snowier.auth.shiro.consts.AuthConsts;
import org.zfes.snowier.auth.shiro.suser.SessionUser;
import org.zfes.snowier.auth.shiro.suser.SessionUserManager;
import org.zfes.snowier.auth.shiro.util.SecurityUtil;
import org.zfes.snowier.cloud.zbss.loan.util.CloudStockConst;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * @Author:Victor
 * @Decription: 微信端登录绑定微信openid
 * @Date:Created in 10:54 2018/4/27
 * @Param:
 * @Modified By:
 */
@RestController
@RequestMapping("/web/wechat/loginApi")
public class UserLoginApi {
    @Autowired
    private IAuthUserService authUserService;
    private IAuthUserRoleService authRoleService;

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private SessionUserManager sessionUserManager;

    @RequestMapping(value="/bindingWechat", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public Object bindingWechat(HttpServletRequest request, HttpServletResponse response, String openId, String account, String password){
       /* JSONObject jsonStr = JSONObject.parseObject(requestJson);
        String opendId = (String) jsonStr.get("opendId");
        String account = (String) jsonStr.get("account");
        String password = (String) jsonStr.get("password");*/

        JSONObject responsResult = new JSONObject();
        if((openId.isEmpty() || openId == null || "undefined".equals(openId)) || (account.isEmpty() || account == null) || (password.isEmpty() || password == null)){
            responsResult.put(CloudStockConst.WebControllerResult.CODE,CloudStockConst.WebControllerCode.STATUS_CODE_201);
            responsResult.put(CloudStockConst.WebControllerResult.ERROR,"参数不能空！");
            return responsResult;
        }
        Optional<AuthUser> userOp = authUserService.loadByAccount(account);
        String salt = "";

        if(userOp.isPresent()){
            salt = userOp.get().getSalt();
        }else{
            responsResult.put(CloudStockConst.WebControllerResult.CODE,CloudStockConst.WebControllerCode.STATUS_CODE_201);
            responsResult.put(CloudStockConst.WebControllerResult.ERROR,"用户名错误！");
            return responsResult;
        }

        //String pwd1 = ShiroMD5EndecryptUtil.genSetp1Password(password);

        //String entryPassword=ShiroMD5EndecryptUtil.genSetp2Password(pwd1, salt);
        Optional<AuthUser> user = null;
         //authUserService.loadAuthUserByAccountAndPassword(account,entryPassword);
        if(user.isPresent()){
            //user.get().setOpenId(openId);
            authUserService.updateAuthUser(user.get());

            Optional<SessionUser> sessionUserOp = getSessionUserManager().loadSessionUserByAccount(openId);
            SessionUser sessionUser = sessionUserOp.orElse(new SessionUser());
            Subject subject = SecurityUtils.getSubject();
            Session session = subject.getSession();
            if (sessionUserOp.isPresent()) {
                logger.debug("已经注册");
                try {
                   // subject.login(new WeiChatAuthToken(sessionUserOp.get().getUsername(), "anonymous".toCharArray()));
                } catch (AuthenticationException e) {
                    logger.error(e.getMessage());
                }
                sessionUser.setOpenId(openId);

                session.setAttribute(AuthConsts.SESSION.SESSION_USER_KEY, sessionUser);
                session.setAttribute(AuthConsts.SESSION.SESSION_LOGINORGIN_KEY, "WEICHAT");
                responsResult.put(CloudStockConst.WebControllerResult.CODE, CloudStockConst.WebControllerCode.STATUS_CODE_200);
                responsResult.put(CloudStockConst.WebControllerResult.DATA, sessionUser);
            }

        }else{
            responsResult.put(CloudStockConst.WebControllerResult.CODE,CloudStockConst.WebControllerCode.STATUS_CODE_201);
            responsResult.put(CloudStockConst.WebControllerResult.ERROR,"密码错误！");
        }

        return responsResult;
    }


    public SessionUserManager getSessionUserManager() {
        if (sessionUserManager == null) {
           // sessionUserManager = AppCtxUtil.getBean("sessionUserManagerImpl");
        }
        return sessionUserManager;
    }

    @RequestMapping(value="/getUserInfo", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public Object getUserInfo(HttpServletRequest request, HttpServletResponse response){
        Map<String,Object> map = Maps.newHashMap();

        SessionUser u = SecurityUtil.getSessionUser().get();
        //List<Long> roleIds = authRoleService.loadRoleIdsInUserRoleByUserId(u.getUserId(), "APP_ROOT", true);
        //if(roleIds != null && roleIds.size() > 0){
        //    u.setRoleId(roleIds.get(0));
        //}
        map.put("userInfo",u);
        return map;
    }
}
